<template>
  <view>
    <el-form
      ref="form"
      v-if="formData && field"
      :model="formData"
      :rules="rules"
      label-width="120px"
    >
      <data-form-block
        memo="基础信息"
        :metas="field"
        v-model:form-data="formData"
      ></data-form-block>
      <template v-for="(val, key) in blockMeta" :key="key">
        <template v-if="key === 'default'">
          <data-form-block
            memo="扩展信息"
            :metas="val"
            v-model:form-data="formData"
          ></data-form-block>
        </template>
        <template v-else>
          <data-form-block
            :memo="val[0].blockMemo"
            :metas="val"
            v-model:form-data="formData[key]"
          ></data-form-block>
        </template>
      </template>
      <template v-for="item in ruleConfig.extendArrays" :key="item.name">
        <el-divider content-position="left">{{ item.memo }}</el-divider>
        <template
          v-for="(_, formIndex) in formData[item.name]"
          :key="formIndex"
        >
          <data-form-array-block
            :metas="item.arrs"
            v-model:formData="formData[item.name][formIndex]"
            :formIndex="formIndex"
            :arrLen="formData[item.name].length"
            :removeItem="() => formData[item.name].splice(formIndex, 1)"
            :pushItem="() => formData[item.name].push({})"
          ></data-form-array-block>
        </template>
      </template>
      <view class="_text-a-c _flex _flex-end">
        <el-button>取消</el-button>
        <el-button type="primary" @click="submit"> 提交 </el-button>
      </view>
    </el-form>
  </view>
</template>

<script>
import ToolAction from "@/tool/http/tool-action.js";
import toolArray from "@/tool/tool-array";
import extension from "../../extension.js";
import DataFormArrayBlock from "./data-form-array-block.vue";
import DataFormBlock from "./data-form-block.vue";
import toolJson from "@/tool/tool-json.js";

let api;
let ruleConfig = {};
let emptyFormData = {};

export default {
  components: { DataFormBlock, DataFormArrayBlock },
  props: {
    dataId: {
      type: String,
      default: undefined,
    },
    dataCode: {
      type: String,
      require: true,
    },
    fixParam: {
      type: Object,
      default: () => {},
    },
  },
  data() {
    return {
      formData: undefined,
      ruleConfig: { extendFields: [], extendArrays: [] },
    };
  },
  computed: {
    field() {
      return [
        ...this.ruleConfig.metadata.filter(
          (item) =>
            // 隐藏参数过滤
            !item.hidden &&
            // 扩展参数过滤
            this.ruleConfig.extendField !== item.name &&
            // 固定参数过滤
            !Object.keys(this.fixParam || {}).includes(item.name) &&
            // 插件参数过滤 - 只在列表进行插件属性配置，编辑页面不进行 20230420 lwj
            !item.component &&
            item.name !== "created_date"
        ),
      ];
    },
    extendMeta() {
      return this.ruleConfig.extendFields.filter(
        (item) => !item.is || item.is(this.formData)
      );
    },
    blockMeta() {
      return toolArray.groupBy(this.extendMeta, "block");
    },
    rules() {
      let rules = {};
      // this.field.forEach(item => {
      // 	rules[item.name] = []
      // });
      return rules;
    },
  },
  mounted() {
    api = ToolAction.init(this.dataCode);
    this.init();
  },
  methods: {
    async init() {
      await this.loadMetaData();
      await this.loadView();
    },
    async loadMetaData() {
      ruleConfig = this.ruleConfig = await extension.init(this.dataCode);
      // this.ruleConfig.extendFields.forEach((item) => {
      //   emptyFormData[item.name] =
      //     item.dictList && item.dictList.length > 0 ? [] : undefined;
      // });
      this.ruleConfig.extendArrays.forEach((item) => {
        emptyFormData[item.name] = [{}];
      });
    },
    submit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          api
            .sync({
              ...onFormSubmit(this.formData),
              ...this.fixParam,
              id: this.dataId,
            })
            .then(() => {
              this.$emit("close");
            });
        }
      });
    },
    async loadView() {
      let viewData = {};
      if (this.dataId) {
        viewData = await api.view({ id: this.dataId });
      }
      this.formData = initForm({
        ...emptyFormData,
        ...viewData,
      });
      // 初始化块级表单对象为空的情况
      Object.keys(this.blockMeta).forEach((key) => {
        if (!this.formData[key]) {
          this.formData[key] = {};
        }
      });
    },
  },
};

function initForm(form = {}) {
  let extendVal = form[ruleConfig.extendField];
  if (extendVal) {
    ruleConfig.extendFields.forEach((meta) => {
      if (meta.name.startsWith("__")) {
        meta.name = meta.name.substring(2);
      }
      if (meta.block) {
        form[meta.block] = toolJson.parse(extendVal[meta.block]);
      } else {
        form[meta.name] = extendVal[meta.name];
      }
    });
    ruleConfig.extendArrays.forEach((meta) => {
      form[meta.name] =
        extendVal[meta.name] || JSON.parse(extendVal[meta.name] || "[{}]");
    });
    // Object.keys(extendVal).forEach((key) => {
    //   form["__" + key] = extendVal[key];
    // });
  }
  return { ...form };
}

function onFormSubmit(formOrigin = {}) {
  formOrigin = JSON.parse(JSON.stringify(formOrigin));
  const extendObj = {};
  // 扩展数据转换
  ruleConfig.extendFields.forEach((meta) => {
    if (meta.name.startsWith("__")) {
      meta.name = meta.name.substring(2);
    }
    if (meta.block && !extendObj[meta.block]) {
      extendObj[meta.block] = formOrigin[meta.block] || {};
    } else {
      extendObj[meta.name] = formOrigin[meta.name];
    }
    delete formOrigin[meta.block || meta.name];
  });
  ruleConfig.extendArrays.forEach((meta) => {
    extendObj[meta.name] = formOrigin[meta.name] || [];
    delete formOrigin[meta.name];
  });
  // Object.keys(formOrigin)
  //   .filter((item) => item.startsWith("__"))
  //   .forEach((item) => {
  //     extendObj[item.substr(2)] = formOrigin[item];
  //     delete formOrigin[item];
  //   });
  // 临时数据清理
  Object.keys(formOrigin)
    .filter((item) => item.startsWith("_"))
    .forEach((item) => {
      delete formOrigin[item];
    });
  if (Object.keys(extendObj).length) {
    formOrigin[ruleConfig.extendField] = JSON.stringify(extendObj);
  }
  return formOrigin;
}
</script>

<style scoped></style>
